package com.meteor.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.meteor.admin.dto.LoginDTO;
import com.meteor.admin.dto.ResponseDTO;
import com.meteor.admin.entity.User;
import com.meteor.admin.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @ResponseBody
    @PostMapping("/login")
    public ResponseDTO<String> login(@RequestBody LoginDTO loginDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginDTO.getUsername());
        User user = userMapper.selectOne(queryWrapper);

        if (user != null) {
            return ResponseDTO.ok();
        } else {
            return ResponseDTO.error("用户名或密码错误");
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/login";
    }
}